# -*- coding: UTF-8 -*-
from typing import List
from leetcode_helper import TestcaseHelper, SolutionBase


class Solution(SolutionBase):
    # 解题的方法，命名和Leetcode的保持一致即可
    def minSwaps(self, nums: List[int]) -> int:
        count_one = sum(nums)

        if count_one == 0 or count_one == 1:
            return 0

        one_in_window = 0
        ret_val = count_one
        nums_len = len(nums)

        # 计算初始的窗口（从nums[0]开始）内1的数量
        for i in range(count_one):
            one_in_window += nums[i]

        # 计算初始的移动次数
        ret_val = min(count_one, count_one - one_in_window)

        # 环形数组的长度是原数组长度加上滑动窗口的长度
        # i 表示要加入到滑动窗口的新元素
        for i in range(1, nums_len):
            # 计算移出的原属
            sub_value = nums[i - 1]

            # 计算追加的原属
            add_value = 0
            if i + count_one - 1 < nums_len:
                add_value = nums[i + count_one - 1]
            else:
                add_value = nums[i + count_one - 1 - nums_len]

            # 计算新的窗口里1的个数
            one_in_window = one_in_window + add_value - sub_value
            ret_val = min(ret_val, count_one - one_in_window)

            # 如果窗口里全是1，说明不用移动
            if ret_val == 0:
                break

        return ret_val


if __name__ == '__main__':
    solution = Solution()

    # 按照leetcode的题目说明，将基本的test case填入
    # 每条case的最后一个元素是正确的结果，即期待的结果
    # 使用元组来保存输入的数据，期待的结果
    testcases = [
        ([1,1,0,0,0,1,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,1,0,0,1,1,1,0,0,0,0,0,1,1,1,1,0,1,1,0,1,1], 7),
        ([0, 1, 0, 1, 1, 0, 0], 1),
        ([0, 1, 1, 1, 0, 0, 1, 1, 0], 2),
        ([1, 1, 0, 0, 1], 0)
    ]

    for case_item in testcases:
        input1 = case_item[0]
        expect = case_item[len(case_item) - 1]
        # TODO: 调用对应方法，需要替换具体的方法
        exec_result = solution.minSwaps(input1)

        # 判断执行结果，输出提示信息
        check_result = solution.check_result(expect, exec_result)
        TestcaseHelper.print_case(check_result, case_item, exec_result)

